/* ***************************
* 电子表格和数据图表操作界面公共部分JS
* @Editer wangjunfu
* ****************************/

//数据源 切换显示
$("#unfole-cube").click(function () {
    var b = $("#optionmaindiv").hasClass("no-cube");
    if (b) {
        $("#optionmaindiv").removeClass("no-cube");
    } else {
        $("#optionmaindiv").addClass("no-cube");
    }
});

//可视化编辑
$("#unfold-widget").click(function () {
    var b = $("#optionmaindiv").hasClass("no-widget");
    if (b) {
        $("#optionmaindiv").removeClass("no-widget");
    } else {
        $("#optionmaindiv").addClass("no-widget");
    }
});

//关闭数据源面板
$("#close-main-cube").click(function () {
    $("#optionmaindiv").addClass("no-cube");
});

//关闭可视化编辑面板
$("#close-main-widget").click(function () {
    $("#optionmaindiv").addClass("no-widget");
});

//字段搜索事件
$("#fieldSearchInput").keyup(function () {
    var keyword = $(this).val();
    $("#dim_tree").find("li").hide();
    if (keyword === "") {
        $("#dim_tree").find("li").show();
    } else {
        $("#dim_tree").find("li:contains('" + keyword + "')").show();
    }
});

//字段搜索框失去焦点并且内容为空时 隐藏搜索input
$("#fieldSearchInput").blur(function () {
    var keyword = $(this).val();
    if (keyword === "") {
        $("#fieldSearchInput").addClass("hide");
    }
});

//字段点击选中
$("#dim_tree").find("li > a").click(function () {
    $("#dim_tree").find("li > a").removeClass("curSelectedNode");
    $(this).addClass("curSelectedNode");
});

// 展开折叠字段树
function openCloseFieldTree(fobj) {
    var li = $(fobj).closest("li");
    var t = $(fobj);
    var b = t.hasClass("center_open");
    if (b) {
        t.removeClass("center_open");
        t.addClass("center_close");
        li.find("ul").slideUp();
    } else {
        t.removeClass("center_close");
        t.addClass("center_open");
        li.find("ul").slideDown();
    }
}

//数据源 点击显示字段搜索框
function showFieldSearchInput() {
    $("#fieldSearchInput").removeClass("hide");
}

//元数据字段拖拽动作
$("#dim_tree").find("a[candrag=true]").draggable({appendTo: "body", helper: "clone"});

/**
 * 拖拽到过滤条件处事件
 */
$("#filter_droppable").droppable({
    activeClass: "ui-state-default",
    hoverClass: "ui-state-hover",
    drop: function (event, ui) {
        var field_a = $(ui.draggable);
        var name = field_a.data("fname");
        var namecn = field_a.data("fnamecn");
        var type = field_a.data("ftype");
        var field = {};
        field.colName = name;
        field.colNameCn = namecn;
        field.colType = type;
        switch (type) {
            case "string":
            case "enum":
            case "text":
                showStringFilterModal(field);
                break;
            case "date":
                destroyAbsoluteDate();
                showDateFilterModal(field);
                break;
            case "datetime":
            case "numeric":
                showNumberFilterModal(field);
                break;
            case "filter":
                //处理预设条件字段
                createPresetFilter(name);
                break;
            default:
                showInfoAlert("[" + type + "]类型字段不能作为过滤条件！");
                break;
        }
    }
});

/**
 * 处理设置好的过滤条件字段
 */
function createPresetFilter(filterFieldName) {
    //先找到该过滤字段类型对象 _meta_col_map该对象在html页面
    var filterField = _meta_col_map[filterFieldName];
    if (!filterField) {
        return showInfoAlert("元数据中没有名称为【" + filterFieldName + "】过滤类型字段！");
    }
    //获取预设的过滤字符串
    var filter_str = filterField.colMark;
    if (filter_str === "") {
        return showInfoAlert("【" + filterFieldName + "】过滤类型字段预设的过滤条件为空！")
    }
    //拆分条件
    var arr_filter_str = filter_str.split("@");
    var error_filters = [];
    for (i in arr_filter_str) {
        var fs = arr_filter_str[i];
        var fieldname = "";
        var fieldnamecn = "";
        var fvalue = "";
        var fromvalue, tovalue, fieldtype;
        var filtertype;
        if (fs.indexOf(" >= ") > 0 || fs.indexOf(" <= ") > 0) {     //范围条件
            filtertype = "range";
            if (fs.indexOf(" >= ") > 0 && fs.indexOf(" <= ") > 0) { //有开始和结束范围
                var arr_range = fs.split(" and ");
                var str = arr_range[0];
                var str2 = arr_range[1];
                if (str.indexOf(" >= ") > 0) {                  //范围开始值在前
                    fieldname = $.trim(str.split(" >= ")[0]);
                    fromvalue = $.trim(str.split(" >= ")[1]);
                    tovalue = $.trim(str2.split(" <= ")[1]);
                } else {
                    fieldname = $.trim(str.split(" <= ")[0]);
                    tovalue = $.trim(str.split(" <= ")[1]);
                    fromvalue = $.trim(str2.split(" >= ")[1]);
                }
            } else if (fs.indexOf(" >= ") > 0) {                //只有开始范围
                fieldname = $.trim(fs.split(" >= ")[0]);
                fromvalue = $.trim(fs.split(" >= ")[1]);
                tovalue = "";
            } else if (fs.indexOf(" <= ") > 0) {                //只有结束范围
                fieldname = $.trim(fs.split(" <= ")[0]);
                fromvalue = "";
                tovalue = $.trim(fs.split(" <= ")[1]);
            }
        } else if (fs.indexOf(" != ") > 0) {                    //不等条件
            filtertype = "notEqual";
            fieldname = $.trim(fs.split(" != ")[0]);
            fvalue = $.trim(fs.split(" != ")[1]);
        } else if (fs.indexOf(" not in ") > 0) {                //not in 条件
            filtertype = "notIn";
            fieldname = $.trim(fs.split(" not in ")[0]);
            fvalue = $.trim(fs.split(" not in ")[1]);
            fvalue = fvalue.substring(1, fvalue.length - 1);    //去掉前后括号
        } else if (fs.indexOf(" in ") > 0) {                    //not in 条件
            filtertype = "in";
            fieldname = $.trim(fs.split(" in ")[0]);
            fvalue = $.trim(fs.split(" in ")[1]);
            fvalue = fvalue.substring(1, fvalue.length - 1);    //去掉前后括号
        } else if (fs.indexOf(" not like ") > 0) {              //not like 条件
            filtertype = "notLike";
            fieldname = $.trim(fs.split(" not like ")[0]);
            fvalue = $.trim(fs.split(" not like ")[1]);
        } else if (fs.indexOf(" like ") > 0) {                  //模糊匹配条件
            filtertype = "like";
            fieldname = $.trim(fs.split(" like ")[0]);
            fvalue = $.trim(fs.split(" like ")[1]);
        } else if (fs.indexOf(" = ") > 0) {                     //等值条件
            filtertype = "equal";
            fieldname = $.trim(fs.split(" = ")[0]);
            fvalue = $.trim(fs.split(" = ")[1]);
        } else {
            error_filters.push("错误的过滤条件格式设置！[" + fs + "]");
            continue;
        }
        var field = _meta_col_map[fieldname];
        if (field) {
            fieldtype = field.colType;
            fieldnamecn = field.colNameCn;
            createFilterDom(fs, fieldname, fieldnamecn, fieldtype, fvalue, filtertype, fromvalue, tovalue);
        } else {
            error_filters.push("元数据表中不存在的字段！[" + fs + "]");
        }
    }
    if (error_filters.length > 0) {
        var error_msg = "快捷过滤条件设置出错了：</br>";
        $.each(error_filters, function (i, msg) {
            error_msg += msg + "</br>"
        });
        showInfoAlert(error_msg);
    }
}

/**
 * 打开创建字符串过滤窗口
 * @param field
 */
function showStringFilterModal(field) {
    $("#string_filter_field_name").val(field.colName);
    $("#string_filter_field_namecn").val(field.colNameCn);
    $("#string_filter_field_type").val(field.colType);

    //in条件设置初始化
    $("#field_all_values_select").empty();
    $("#field_choose_values_select").empty();
    $("#filterValuesInput").val("");
    $("#valuesInput").val("");
    $("#filedFilterModalLabel").text(field.colNameCn + "(" + field.colName + ")");
    //equal条件设置初始化
    $("#stringEqualInput").val("");
    $("#stringEqualLabel").text(field.colName);
    //like条件设置初始化
    $("#stringLikeInput").val("");
    $("#stringLikeLabel").text(field.colName);

    $("#filedFilterModal").modal("show");
    queryFieldValues(field);
}

/**
 * 过滤条件选项卡 增加/移除查询值
 * @param target
 */
function dbClickAddOrRemove(target) {
    var pid = $(target).closest("select").attr("id");
    if ("field_choose_values_select" == pid) {
        $("#field_all_values_select").append($(target));
    }
    if ("field_all_values_select" == pid) {
        $("#field_choose_values_select").append($(target));
    }
}

/**
 * 手动输入查询过滤条件值
 */
function addSelectFilterValues() {
    var values = $("#valuesInput").val();
    if (values === "") {
        return showInfoAlert("输入值不能为空！多个值使用英文逗号\",\"分隔。");
    }
    if (values.indexOf(",") >= 0) {
        var arr_v = values.split(",");
        $.each(arr_v, function (i, v) {
            if (v !== "") {
                $("#field_choose_values_select").append("<option ondblclick='dbclickAddOrRemove(this)' value='" + v + "'>" + v + "</option>");
            }
        });
    } else {
        $("#field_choose_values_select").append("<option ondblclick='dbclickAddOrRemove(this)' value='" + values + "'>" + values + "</option>");
    }
}

/**
 * 自动查询过滤条件值
 * @returns {*}
 */
function queryFieldValuesBtn() {
    var lv = $("#filterValuesInput").val();
    if (lv === "") {
        return showInfoAlert("查询值不能为空！");
    }
    var fname = $("#string_filter_field_name").val();
    var ftype = $("#string_filter_field_type").val();
    var fnamecn = $("#string_filter_field_namecn").val();
    var field = {};
    field.colName = fname;
    field.colNameCn = fnamecn;
    field.colType = ftype;
    queryFieldValues(field);
}

function queryFieldValues(field) {
    var url = "/analysis/spreadsheet/execQuery";

    //执行分组查询吧 改字段所有值都列出来
    var sourceId = $("#sourceId").val();
    var lv = $("#filterValuesInput").val();

    var postdatas = "page=1&pageSize=1000&limitSize=10000&sourceId=" + sourceId + "&";
    postdatas += "queryfields=" + field.colName + "&querynames=" + field.colNameCn + "&queryfieldtypes=" + field.colType + "&queryagg=group&paramsField=[]&";
    postdatas += "queryfields=" + field.colName + "&querynames=" + field.colNameCn + "计数&queryfieldtypes=" + field.colType + "&queryagg=count&paramsField=[]&";

    //添加dt字段
    var dtfield = _meta_col_map["dt"];
    if (dtfield) {
        postdatas += "filterfield=dt&filterftypes=date&filtertype=range&textvalues=&fromvalues=T7&tovalues=T1&";
    }

    //添加过滤条件
    if (lv && lv.length > 0) {
        postdatas += "filterfield=" + field.colName + "&filterftypes=" + field.colType + "&filtertype=like&textvalues=" + lv;
    }

    ajax({
        url: url,
        data: postdatas,
        success: function (result) {
            if (result.returnCode === "1") {
                var select = $("#field_all_values_select");
                select.empty();
                var page = result.page;
                var rows = page.items;
                //数据信息
                if (rows.length > 0) {
                    for (var i = 0; i < rows.length; i++) {
                        var row = rows[i];
                        var gfc = row.values[0];
                        var gf = row.values[1];
                        var option = $("<option ondblclick=' dbClickAddOrRemove(this)' value='" + gf + "'>" + gf + "</option>");
                        select.append(option);
                    }
                }
            } else {
                showInfoAlert(result.returnMessage, null);
            }
        }
    });
}


/**
 * 字符串类型字段默认查询type
 */
var _string_term_type = "in";
function selectStringTermType(type) {
    _string_term_type = type;
}

/**
 * 生成字符串过滤条件
 */
function createStringFilter() {
    var fname = $("#string_filter_field_name").val();
    var ftype = $("#string_filter_field_type").val();
    var fnamecn = $("#string_filter_field_namecn").val();
    var the_term_type = "";     //条件类型 in notIn equal notEqual like notLike
    var trme_str = "";
    var fvalue = "";

    if (_string_term_type == 'in') {
        the_term_type = $("#string_in_notin_select").val();
        var tstr = " in ";
        if (the_term_type == "notIn") {
            tstr = " not in ";
        }
        trme_str = fname + tstr + " (";
        var values_str = "";
        var values = $("#field_choose_values_select").find("option");
        if (values.length === 0) {
            return showInfoAlert("过滤值不能为空！");
        }
        $.each(values, function (i, v) {
            values_str += $(v).attr("value") + ",";
        });
        values_str = values_str.substring(0, values_str.length - 1);
        trme_str = trme_str + values_str + ")";
        fvalue = values_str;
    } else if (_string_term_type == 'equal') {
        the_term_type = $("#string_equal_notequal_select").val();
        fvalue = $("#stringEqualInput").val();
        if (fvalue === "") {
            return showInfoAlert("过滤值不能为空！");
        }
        trme_str = fname + " = " + fvalue;

    } else {
        the_term_type = $("#string_like_notlike_select").val();
        fvalue = $("#stringLikeInput").val();
        if (fvalue === "") {
            return showInfoAlert("过滤值不能为空！");
        }
        trme_str = fname + " like " + fvalue;
    }

    createFilterDom(trme_str, fname, fnamecn, ftype, fvalue, the_term_type);

    //关闭modal
    $("#filedFilterModal").modal("hide");
}

/**
 * 生成数字过滤条件
 */
var number_filter_range = true;

function createNumberFilter() {
    var fname = $("#number_filter_field_name").val();
    var fieldtype = $("#number_filter_field_type").val();
    var fnamecn = $("#number_filter_field_namecn").val();
    var trme_str = "";
    var ftype = "";
    var fvalue = "";
    var fromvalue, tovalue;
    if (number_filter_range) {
        ftype = 'range';
        fromvalue = $("#numberFilterStartInput").val();
        tovalue = $("#numberFilterEndInput").val();
        if (fromvalue !== "" && tovalue !== "") {
            if (fromvalue > tovalue) {
                return showInfoAlert("范围开始值不能大于范围结束值！");
            }
            trme_str = fname + " >= " + fromvalue + " and " + fname + " <= " + tovalue;
        } else if (fromvalue === "" && tovalue === "") {
            return showInfoAlert("范围开始值和结束值不能都为空！");
        } else if (fromvalue === "") {
            trme_str = fname + " <= " + tovalue;
        } else {
            trme_str = fname + " >= " + fromvalue;
        }

    } else {
        ftype = 'equal';
        fvalue = $("#numberFilterInput").val();
        if (fvalue === "") {
            return showInfoAlert("条件值不能为空！");
        }
        trme_str = fname + " = " + fvalue;
    }
    createFilterDom(trme_str, fname, fnamecn, fieldtype, fvalue, ftype, fromvalue, tovalue);
    $("#filedNumberFilterModal").modal("hide");
}

function showNumberFilterRange() {
    number_filter_range = true;
    $("#numberFilterRangeBtn").addClass("btn-primary");
    $("#numberFilterRangeBtn").removeClass("btn-white");

    $("#numberFilterBtn").addClass("btn-white");
    $("#numberFilterBtn").removeClass("btn-primary");
    //范围区间显示
    $("#numberRangeDiv").show();
    $("#numberEqualDiv").hide();
}

function showNumberFilterEqual() {
    number_filter_range = false;
    $("#numberFilterBtn").addClass("btn-primary");
    $("#numberFilterBtn").removeClass("btn-white");

    $("#numberFilterRangeBtn").addClass("btn-white");
    $("#numberFilterRangeBtn").removeClass("btn-primary");
    //范围区间隐藏
    $("#numberEqualDiv").show();
    $("#numberRangeDiv").hide();
}

function showNumberFilterModal(field) {
    $("#number_filter_field_name").val(field.colName);
    $("#number_filter_field_namecn").val(field.colNameCn);
    $("#number_filter_field_type").val(field.colType);

    $("#numberFilterInput").val("");
    $("#numberFilterStartInput").val("");
    $("#numberFilterEndInput").val("");

    $("#filedNumberFilterModalLabel").text(field.colNameCn + "(" + field.colName + ")");
    $("#filedNumberFilterModal").modal("show");

}

$(function () {
    //数值过滤条件
    $("#numberFilterRangeBtn").click(function () {
        showNumberFilterRange();
    });
    $("#numberFilterBtn").click(function () {
        showNumberFilterEqual();
    });
    $("#filedNumberFilterModal").on('hidden.bs.modal', function (e) {
        current_eidt_filter_dom = null;
    })
});


/**
 * 生成时间过滤条件
 */
var date_filter_range = true;       //是否时间区间
var date_filter_relative = true;    //是否相对时间

function createDateFilter() {
    var fname = $("#date_filter_field_name").val();
    var fieldtype = $("#date_filter_field_type").val();
    var fnamecn = $("#date_filter_field_namecn").val();
    var trme_str = "";
    var ftype = "";
    var fvalue = "";
    var fromvalue, tovalue;
    if (date_filter_range) {        //范围条件
        ftype = 'range';
        if (date_filter_relative) { //相对值
            var stv = $("#relativeStartDate").val();
            var etv = $("#relativeEndDate").val();
            if (Number(stv) < Number(etv)) {
                return showInfoAlert("相对开始时间不能大于结束时间！", null);
            }
            trme_str = fname + " >= T" + stv + " and " + fname + " <= T" + etv;
            fromvalue = "T" + stv;
            tovalue = "T" + etv;
        } else {
            //绝对值
            var stv = $("#absoluteStartDate").val();
            var etv = $("#absoluteEndDate").val();
            trme_str = fname + " >= " + stv + " and " + fname + " <= " + etv;
            fromvalue = stv;
            tovalue = etv;
        }
    } else {
        ftype = 'equal';
        if (date_filter_relative) { //相对值
            var stv = $("#relativeStartDate").val();
            trme_str = fname + " = T" + stv;
            fvalue = "T" + stv;
        } else {
            //绝对值
            var stv = $("#datepicker-autoclose").val();
            trme_str = fname + " = " + stv;
            fvalue = stv;
        }
    }
    createFilterDom(trme_str, fname, fnamecn, fieldtype, fvalue, ftype, fromvalue, tovalue);
    $("#filedDateFilterModal").modal("hide");
}

function showDateFilterRange() {
    date_filter_range = true;
    $("#dateFilterRangeBtn").addClass("btn-primary");
    $("#dateFilterRangeBtn").removeClass("btn-white");

    $("#dateFilterBtn").addClass("btn-white");
    $("#dateFilterBtn").removeClass("btn-primary");

    //日期区间显示
    $("#absoluteDateRangeDiv").show();
    $("#absoluteDateDiv").hide();

    //相对结束时间显示
    $("#dateLinkChartSpan").show();
    $("#relativeEndDate").show();
}

function showDateFilterEqual() {
    date_filter_range = false;
    $("#dateFilterBtn").addClass("btn-primary");
    $("#dateFilterBtn").removeClass("btn-white");

    $("#dateFilterRangeBtn").addClass("btn-white");
    $("#dateFilterRangeBtn").removeClass("btn-primary");

    //日期显示
    $("#absoluteDateDiv").show();
    $("#absoluteDateRangeDiv").hide();

    //相对结束时间隐藏
    $("#dateLinkChartSpan").hide();
    $("#relativeEndDate").hide();
}

function showDateFilterRelative() {
    date_filter_relative = true;
    $("#dateFilterRelativeBtn").addClass("btn-primary");
    $("#dateFilterRelativeBtn").removeClass("btn-white");

    $("#dateFilterAbsoluteBtn").addClass("btn-white");
    $("#dateFilterAbsoluteBtn").removeClass("btn-primary");

    //销毁时间组件
    $('#date-range').datepicker('destroy');
    $('#datepicker-autoclose').datepicker('destroy');

    //显示相对层
    $("#relativeDateDiv").show();
}

function showDateFilterAbsolute() {
    date_filter_relative = false;
    $("#dateFilterAbsoluteBtn").addClass("btn-primary");
    $("#dateFilterAbsoluteBtn").removeClass("btn-white");

    $("#dateFilterRelativeBtn").addClass("btn-white");
    $("#dateFilterRelativeBtn").removeClass("btn-primary");

    //初始化时间组件
    $('#date-range').datepicker({
        toggleActive: true,
        format: "yyyy-mm-dd"
    });
    $('#datepicker-autoclose').datepicker({
        autoclose: true,
        todayHighlight: true,
        format: "yyyy-mm-dd"
    });

    //隐藏相对层
    $("#relativeDateDiv").hide();
}

//时间过滤弹层
function showDateFilterModal(field) {
    $("#date_filter_field_name").val(field.colName);
    $("#date_filter_field_namecn").val(field.colNameCn);
    $("#date_filter_field_type").val(field.colType);

    $("#filedDateFilterModalLabel").text(field.colNameCn + "(" + field.colName + ")");
    $("#filedDateFilterModal").modal("show");
}

//销毁绝对时间组件（只在拖拽时使用）
function destroyAbsoluteDate() {
    //销毁时间组件
    $('#date-range').datepicker('destroy');
    $('#datepicker-autoclose').datepicker('destroy');
}

$(function () {
    //时间过滤条件
    $("#dateFilterRangeBtn").click(function () {
        showDateFilterRange();
    });

    $("#dateFilterBtn").click(function () {
        showDateFilterEqual();
    });

    $("#dateFilterRelativeBtn").click(function () {
        showDateFilterRelative();
    });

    $("#dateFilterAbsoluteBtn").click(function () {
        showDateFilterAbsolute();
    });

    //相对时间
    $("#relativeDateTNBtn button").click(function () {
        var tn = $(this).data("t1t4");
        $(this).addClass("btn-success");
        $(this).removeClass("btn-white");
        $(this).closest("div").siblings().find("button").removeClass("btn-success");
        $(this).closest("div").siblings().find("button").addClass("btn-white");

        //相对赋值
        $("#relativeStartDate").val(tn);
        $("#relativeEndDate").val(1);

        //绝对赋值
        var dateTn = moment().subtract(tn, 'days').format("YYYY-MM-DD");
        $("#absoluteStartDate").val(dateTn);
        $("#datepicker-autoclose").val(dateTn);

        var dateT1 = moment().subtract(1, 'days').format("YYYY-MM-DD");
        $("#absoluteEndDate").val(dateT1);
    });

    //相对开始时间修改后，显示下其对应于今天的绝对时间
    $("#relativeStartDate").change(function () {
        var stv = $(this).val();
        var etv = $("#relativeEndDate").val();
        if (stv < etv) {
            return showInfoAlert("相对开始时间不能大于结束时间！");
        }
        var datev = moment().subtract(stv, 'days').format("YYYY-MM-DD");
        $("#absoluteStartDate").val(datev);
        $("#datepicker-autoclose").val(datev);
    });

    $("#relativeEndDate").change(function () {
        var stv = $("#relativeStartDate").val();
        var etv = $("#relativeEndDate").val();
        if (stv < etv) {
            return showInfoAlert("相对开始时间不能大于结束时间！");
        }
        var datev = moment().subtract(etv, 'days').format("YYYY-MM-DD");
        $("#absoluteEndDate").val(datev);
    });

    //时间过滤条件操作窗口关闭
    $("#filedDateFilterModal").on('hidden.bs.modal', function (e) {
        current_eidt_filter_dom = null;
    })
});


$(function () {
    //过滤条件操作窗口关闭
    $("#filedFilterModal").on('hidden.bs.modal', function (e) {
        current_eidt_filter_dom = null;
    });

    //过滤条件选择值按钮事件
    $("#fieldSelectChooseBtn").click(function () {
        $("#field_choose_values_select").append($("#field_all_values_select").find(":selected"));
    });
    $("#fieldUnselectChooseBtn").click(function () {
        $("#field_all_values_select").append($("#field_choose_values_select").find(":selected"));
    });
    $("#fieldUnselectAllBtn").click(function () {
        $("#field_all_values_select").append($("#field_choose_values_select").find("option"));
    });
    $("#fieldSelectAllBtn").click(function () {
        $("#field_choose_values_select").append($("#field_all_values_select").find("option"));
    });
});